import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;


import java.io.IOException;

/**
 * Created by manatea on 2016/6/14.
 */
public class DataMax {
    public static class CZMapper extends Mapper<LongWritable, Text, Text, DataBean> {
        @Override
        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String[] field = line.split("\t");
            String name = "";
            long age;
            DataBean dataBean = null;
            if (field.length > 0) {
                name = field[0];
                age = Long.valueOf(field[1]);
                dataBean = new DataBean(name, age);
            }
            context.write(new Text(name), dataBean);
        }
    }

    public static class CZReducer extends Reducer<Text, DataBean, Text, DataBean> {
        @Override
        public void reduce(Text key, Iterable<DataBean> values, Context context) throws IOException, InterruptedException {
            long sum = 0;
            for (DataBean dataBean : values) {
                sum += dataBean.getAge();
            }
            context.write(key, new DataBean(key.toString(), sum));
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration configuration = new Configuration();
        Job job = Job.getInstance(configuration);
        job.setJarByClass(DataMax.class);

        job.setMapperClass(CZMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(DataBean.class);
        FileInputFormat.addInputPath(job,new Path("input"));
        job.setReducerClass(CZReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(DataBean.class);
        FileOutputFormat.setOutputPath(job,new Path("output"));

        job.waitForCompletion(true);
//        BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("input")));
//        byte[] buf = new byte[1024];
//        String s;
//        while ((s = bufferedReader.readLine()) != null) {
//            String[] fields = s.split("\t");
//            System.out.println(fields[0]+fields[1]);
//        }
    }
}
